package com.lehecai.core.search.api.impl;

import com.lehecai.core.search.api.ISearchApiRequest;
import com.lehecai.core.search.api.ISearchApiRequestBody;
import com.lehecai.core.search.api.SearchApiConstant;
import com.lehecai.core.search.type.SearchEntityKey;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 搜索服务请求抽象类
 * User: sunshow
 * Date: 13-3-31
 * Time: 下午2:01
 */
public abstract class AbstractSearchApiRequest implements ISearchApiRequest {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    private SearchEntityKey service;

    private long serial;

    private ISearchApiRequestBody body;

    @Override
    public JSON toJSON() {
        JSONObject jsonObject = new JSONObject();

        jsonObject.put(SearchApiConstant.API_PARAMETER_SERVICE, this.getService().getName());
        jsonObject.put(SearchApiConstant.API_PARAMETER_COMMAND, this.getCommand());
        jsonObject.put(SearchApiConstant.API_PARAMETER_SERIAL, this.getSerial());

        if (this.getBody() != null) {
            jsonObject.put(SearchApiConstant.API_PARAMETER_BODY, this.getBody().toJSON());
        }

        return jsonObject;
    }

    @Override
    public SearchEntityKey getService() {
        return this.service;
    }

    @Override
    abstract public String getCommand();

    @Override
    public long getSerial() {
        if (this.serial > 0) {
            return this.serial;
        }
        if (this.getCommand().equals(SearchApiConstant.API_COMMAND_INSERT)) {
            return SearchApiConstant.SERIAL_DEFAULT_INSERT;
        }
        if (this.getCommand().equals(SearchApiConstant.API_COMMAND_SELECT)) {
            return SearchApiConstant.SERIAL_DEFAULT_SELECT;
        }
        if (this.getCommand().equals(SearchApiConstant.API_COMMAND_UPDATE)) {
            return SearchApiConstant.SERIAL_DEFAULT_UPDATE;
        }
        if (this.getCommand().equals(SearchApiConstant.API_COMMAND_DELETE)) {
            return SearchApiConstant.SERIAL_DEFAULT_DELETE;
        }
        if (this.getCommand().equals(SearchApiConstant.API_COMMAND_AGGREGATE)) {
            return SearchApiConstant.SERIAL_DEFAULT_AGGREGATE;
        }
        return 0;
    }

    @Override
    public ISearchApiRequestBody getBody() {
        return this.body;
    }

    public void setService(SearchEntityKey service) {
        this.service = service;
    }

    public void setSerial(long serial) {
        this.serial = serial;
    }

    public void setBody(ISearchApiRequestBody body) {
        this.body = body;
    }
}
